package com.czy.booktest02.demos.service.impl;

import com.czy.booktest02.demos.common.dtos.ResponseResult;
import com.czy.booktest02.demos.common.enums.AppHttpCodeEnum;
import com.czy.booktest02.demos.common.redis.CacheService;
import com.czy.booktest02.demos.common.redis.RedisKey;
import com.czy.booktest02.demos.mapper.UserMapper;
import com.czy.booktest02.demos.pojo.dto.UserDto;
import com.czy.booktest02.demos.pojo.dto.UserLoginDto;
import com.czy.booktest02.demos.pojo.po.User;
import com.czy.booktest02.demos.pojo.vo.UserVO;
import com.czy.booktest02.demos.service.UserService;
import com.czy.booktest02.demos.utils.AlgorithmUtils;
import com.czy.booktest02.demos.utils.AppJwtUtil;
import com.czy.booktest02.demos.utils.BaseUtils;
import com.czy.booktest02.demos.utils.ThreadPoolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CacheService cacheService;
    @Override
    public ResponseResult login(UserLoginDto userDto) {
        User userAccount = userMapper.selectAccount(userDto.getName());
        if (userAccount==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        String productSecretByAlgorithm = AlgorithmUtils.productSecretByAlgorithm(
                userDto.getPwd(),
                AlgorithmUtils.Algorithm.MD5_Algorithm
        );
        if(!productSecretByAlgorithm.equals(userAccount.getPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        //设置token
        String token = AppJwtUtil.getToken(String.valueOf(userAccount.getId()));
        //开线程,异步调用
        keepToRedis(userAccount);
        UserVO userVO = BaseUtils.copyProperties(userAccount, UserVO.class);
        return ResponseResult.okResult(userVO.setToken(token));
    }

    @Override
    public ResponseResult register(UserDto userDto) {
        //判断账户是否已经存在
        User userAccount = userMapper.selectAccount(userDto.getName());
        if(userAccount!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        User user = userMapper.isExist(userDto);
        if(user!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //注册
        User registerUser = BaseUtils.copyProperties(userDto, User.class);
        if(userDto.getGender().equals("男")){
            registerUser.setGender(1);
        }else{
            registerUser.setGender(2);
        }
        String salt= UUID.randomUUID().toString().replaceAll("-", "");
        registerUser.setSalt(salt);
        registerUser.setRegistrationDate(new Date());
        String productSecretByAlgorithm = AlgorithmUtils.productSecretByAlgorithm(
                userDto.getPwd(),
                AlgorithmUtils.Algorithm.MD5_Algorithm
        );
        registerUser.setPassword(productSecretByAlgorithm);
        int insert = userMapper.insert(registerUser);
        if(insert==0){
            return  ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult banByAdmin(int id) {
        if(id>0) {
            int i = userMapper.banUser(id);
            if(i>0){
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }

    @Async
    public void keepToRedis(User userAccount){
        ThreadPoolUtils.putOperationToThread(()->{
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("userId",userAccount.getId());
            parameterMap.put("isAdmin",userAccount.getPermission());
            parameterMap.put("accountStatus",userAccount.getStatus());
            //存储到redis
            cacheService.setMap(RedisKey.USER_INFORMATION+userAccount.getId(),parameterMap);
        });

    }

    @Override
    public ResponseResult selectAllUser() {
        List<User> userList = userMapper.selectAllUser();
        List<UserVO> userVOS = new ArrayList<>();
        if(userList!=null) {
            for (User user : userList) {
                UserVO userVO = BaseUtils.copyProperties(user, UserVO.class);
                userVOS.add(userVO);
            }
        }
        return ResponseResult.okResult(userVOS);
    }

    @Override
    public ResponseResult updateUserStatus(int id,boolean flag) {
        int i=0;
        int status=-1;
        if(!flag){
            //禁用
            status=0;
            i=userMapper.updateStatus(id,status);
        }else{
            //启用
            status=1;
            i=userMapper.updateStatus(id,status);
        }
        if(i>0) return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

        return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
    }

    @Override
    public ResponseResult deleteUser(int id) {
        if(userMapper.deleteUserById(id)>0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);

    }

    @Override
    public ResponseResult setPermission(int id,int permission) {
        if(userMapper.setPermission(id,permission)>0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.FAILURE);
    }
}
